define(['util', 'ajax'], function (util, ajax) {
    "use strict";

    var exports = {}, Section, ViewModel;

    Section = function(title, href, selected) {
        var self = this;
        self.name = title;

        self.href = href;

        self.isSelected = ko.computed(function() {
            return self === selected();
        }, self);

        self.paneCss = ko.computed(function () {
            var css = "tab-pane";
            if (self.isSelected()) {
                css += " active in";
            }
            return css;
        });

        self.isLoaded = false;
    };

    ViewModel = function() {
        var self = this;

        self.selectedSection = ko.observable();

        self.sections = ko.observableArray([]);

        self.selectedSectionName = function () {
            var selected = self.selectedSection();
            if (!selected) return 'NO ELEMENT';
            return selected.name;
        };

        self.loadPartial = function (element, index, section) {
            //console.log($(element).get(0).tagName);
            if (!$(element).is('div')) return;

             if (section.isLoaded) return;
             section.isLoaded = true;
             //var url = "/" + section.name.replace("_", "/");
             $(element).load(section.href);
        };

        $.subscribe('showPicker', function (name, href) {
            var section = _.find(self.sections(), function (s) { return s.name == name; });
            if (!section) {
                section = new Section(name, href, self.selectedSection);
                self.sections.push(section);
            }
            
            self.selectedSection(section);
            $('#ModalBox').modal('show');
        });

        $.subscribe("removeCurrentPickerPane", function() {
            self.sections.remove(self.selectedSection());
        });

        $.subscribe('hidePicker', function () {
            $('#ModalBox').modal('hide');
        });

    };

    exports.exec = function (sectionId) {
        var viewModel = new ViewModel();
        ko.applyBindings(viewModel, document.getElementById(sectionId));

        $('#ModalBox').on('click', 'a', function (event) {
            event.stopPropagation();
            event.preventDefault();

            var dataEvent = $(this).data('event');
            var dataTitle = $(this).data('title');
            var dataUrl = $(this).attr("href");
            var koObj = ko.dataFor(this);
            $.publish(dataEvent, [dataTitle, dataUrl, koObj]);
        });

    };

    return exports;
});

//id="ModalTabTemplate"